package com.example.apigateway.filter;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;


import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

/**
 * \* @author: bear
 * \* Date: 2022-04-08-14:23
 * \* describe:
 */
@Component
public class ConsumerFilter extends ZuulFilter {
	@Override
	public String filterType() {
		return PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return SEND_ERROR_FILTER_ORDER - 1;
	}

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletResponse response = context.getResponse();
		HttpServletRequest request = context.getRequest();
		//往header头里设置
		response.setHeader("X-Foo", UUID.randomUUID().toString());
		// 进行token校验
		String token = request.getParameter("token");
		if (StringUtils.isEmpty(token)) {
			context.setSendZuulResponse(false);
			context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
		}
		return null;
	}
}
